'use strict';
const db = uniCloud.database();
const dbCmd = db.command;

/**
 * 云函数：提交 PK 答案
 * @param {Object} event - 请求参数
 * @param {string} event.pk_id - PK 记录ID
 * @param {string} event.user_id - 用户ID
 * @param {Array} event.answers - 答案列表 [{ question_id, user_answer }]
 * @returns {Object} - 提交结果
 */
exports.main = async (event, context) => {
  const { pk_id, user_id, answers } = event;
  try {
    const pkCollection = db.collection('pk_records');
    const userCollection = db.collection('users');
    const questionCollection = db.collection('questions');
    const answerHistoryCollection = db.collection('answer_history');

    // 获取 PK 记录
    const pkRes = await pkCollection.doc(pk_id).get();
    if (!pkRes.data.length) {
      return { code: -1, msg: 'PK记录不存在' };
    }
    const pk = pkRes.data[0];

    // 验证权限
    if (pk.challenger_id !== user_id && pk.opponent_id !== user_id) {
      return { code: -1, msg: '无权提交答案' };
    }

    // 获取题目
    const questionIds = answers.map(a => a.question_id);
    const questionRes = await questionCollection.where({ _id: dbCmd.in(questionIds) }).get();
    const questions = questionRes.data;

    // 优化：将题目转为哈希表以提高查找效率
    const questionMap = {};
    questions.forEach(q => (questionMap[q._id] = q));

    // 计算分数和答对题目数量
    let score = 0;
    let correctCount = 0; // 新增：统计答对题目数量
    const historyRecords = [];

    for (const answer of answers) {
      const question = questionMap[answer.question_id];
      if (!question) {
        console.warn(`题目 ${answer.question_id} 不存在，跳过处理，answers=${JSON.stringify(answers)}`);
        continue;
      }

      // 验证答案格式，支持字母 A, B, C, D
      if (!['A', 'B', 'C', 'D'].includes(answer.user_answer)) {
        console.warn(`答案格式错误: question_id=${answer.question_id}, user_answer=${answer.user_answer}, 期望格式=['A', 'B', 'C', 'D']`);
        continue;
      }

      // 比较答案
      const isCorrect = answer.user_answer === question.answer;
      if (isCorrect) {
        score += 2; // 每题正确 2 分
        correctCount += 1; // 答对题目计数加 1
      }

      // 记录答题历史
      historyRecords.push({
        user_id,
        question_id: answer.question_id,
        answer: answer.user_answer,
        correct_answer: question.answer,
        correct: isCorrect,
        answered_at: new Date(),
        explanation: question.explanation || ''
      });
    }

    // 更新 PK 记录
    const isChallenger = user_id === pk.challenger_id;
    const updateData = isChallenger
      ? { challenger_answers: answers, challenger_score: score }
      : { opponent_answers: answers, opponent_score: score };

    await pkCollection.doc(pk_id).update(updateData);

    // 批量插入答题历史
    if (historyRecords.length > 0) {
      await Promise.all(historyRecords.map(hr => answerHistoryCollection.add(hr)));
    }

    // 检查双方是否都已提交
    const updatedPk = (await pkCollection.doc(pk_id).get()).data[0];
    if (updatedPk.challenger_answers.length && updatedPk.opponent_answers.length) {
      // 计算胜负
      let winner_id = null;
      let challenger_points = updatedPk.challenger_score;
      let opponent_points = updatedPk.opponent_score;

      if (updatedPk.challenger_score > updatedPk.opponent_score) {
        winner_id = updatedPk.challenger_id;
        challenger_points += 5; // 胜利额外 5 分
      } else if (updatedPk.opponent_score > updatedPk.challenger_score) {
        winner_id = updatedPk.opponent_id;
        opponent_points += 5;
      } else {
        challenger_points += 2; // 平局各加 2 分
        opponent_points += 2;
      }

      // 更新用户积分
      await userCollection.where({ _id: updatedPk.challenger_id }).update({
        points: dbCmd.inc(challenger_points),
        updated_at: new Date()
      });
      await userCollection.where({ _id: updatedPk.opponent_id }).update({
        points: dbCmd.inc(opponent_points),
        updated_at: new Date()
      });

      // 更新 PK 状态
      await pkCollection.doc(pk_id).update({ status: 'completed', winner_id });
    }

    return {
      code: 0,
      data: { score, correctCount }, // 新增：返回答对题目数量
      msg: '答案提交成功'
    };
  } catch (e) {
    console.error('提交PK答案失败:', e);
    return { code: -1, msg: `提交PK答案失败: ${e.message || '未知错误'}` };
  }
};